import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';

export interface CheckInDto {
  id: number;
  courseId: number;
  courseTitle: string;
  studentId: number;
  studentName: string;
  checkInTime: string;
}

export interface CheckInCreateRequest {
  studentId: number;
  courseId: number;
}

export interface CheckInStatsDto {
  courseId: number;
  courseTitle: string;
  studentId: number;
  studentName: string;
  totalCheckIns: number;
  totalSessions: number;
  checkInRate: number;
}

export const useCheckInStore = defineStore('checkIn', {
  state: () => ({
    checkIns: [] as CheckInDto[],
    stats: [] as CheckInStatsDto[],
  }),

  actions: {
    async createCheckIn(data: CheckInCreateRequest) {
      try {
        const response = await axios.post('/api/check-in', data);
        if (response.data.code === 200) {
          return response.data.data;
        }
        throw new Error(response.data.message || '签到失败');
      } catch (error: any) {
        ElMessage.error(error.message || '签到失败');
        throw error;
      }
    },

    async fetchCheckInsByCourse(courseId: number) {
      try {
        const response = await axios.get(`/api/check-in/course/${courseId}`);
        if (response.data.code === 200) {
          this.checkIns = response.data.data;
          return this.checkIns;
        }
        throw new Error(response.data.message || '获取签到记录失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取签到记录失败');
        throw error;
      }
    },

    async fetchCheckInsByStudent(studentId: number) {
      try {
        const response = await axios.get(`/api/check-in/student/${studentId}`);
        if (response.data.code === 200) {
          this.checkIns = response.data.data;
          return this.checkIns;
        }
        throw new Error(response.data.message || '获取签到记录失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取签到记录失败');
        throw error;
      }
    },

    async deleteCheckIn(id: number) {
      try {
        const response = await axios.delete(`/api/check-in/${id}`);
        if (response.data.code === 200) {
          this.checkIns = this.checkIns.filter(item => item.id !== id);
          ElMessage.success('删除成功');
          return response.data.data;
        }
        throw new Error(response.data.message || '删除失败');
      } catch (error: any) {
        ElMessage.error(error.message || '删除失败');
        throw error;
      }
    },

    async fetchStatsByCourse(courseId: number) {
      try {
        const response = await axios.get(`/api/check-in/stats/course/${courseId}`);
        if (response.data.code === 200) {
          this.stats = response.data.data;
          return this.stats;
        }
        throw new Error(response.data.message || '获取统计数据失败');
      } catch (error: any) {
        ElMessage.error(error.message || '获取统计数据失败');
        throw error;
      }
    },
  },
});